package com.yonyou.cyxdms.sysAuth.service.service.impl;

import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.function.bean.dto.http.RestServiceResponseDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.service.UserAuthService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.feign.JDMSUserAuthClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 定义GMMC 的用户认证信息
 *
 * @author: zhangxianchao
 * @since: 2018/9/22 0022
 * @updateDate:
 * @updateRemark:
 * @version:1.0 Copyright: Copyright (c) 2018
 */
@Service(UserAuthConstant.SERVICE_NAME_USER_AUTH + UserAuthConstant.APP_SOURCE_JDMS)
@Transactional(rollbackFor = Exception.class)
public class JDMSUserAuthServiceImpl implements UserAuthService {

    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(JDMSUserAuthServiceImpl.class);
    @Autowired
    public UserService userService;
    @Value("${user-auth." + UserAuthConstant.APP_SOURCE_JDMS + ".auth-url}")
    private String jdmsAuthUrl;
    @Autowired
    JDMSUserAuthClient jdmsUserAuthClient;

    /**
     * 根据主应用的用户信息获取自己应用的用户信息
     *
     * @param token 主应用的用户信息
     * @return org.springframework.http.ResponseEntity
     * @author zhangxianchao
     * @since 2018/9/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public LoginInfoDto getAppUserInfo(String token) {
        //根据token 获取用户信息
        RestServiceResponseDto responseDto = jdmsUserAuthClient.getMainAppUserInfo(jdmsAuthUrl, token);
        if (responseDto.getResultCode() == RestServiceResponseDto.SUCCESS) {
            RestResultResponse resultResponse = com.yonyou.cyx.function.utils.jsonserializer.JSONUtil.jsonToObj(responseDto.getResponseMsg(), RestResultResponse.class);
            logger.debug("userCode:{},appId:{}", resultResponse.getData().toString(), UserAuthConstant.APP_SOURCE_JDMS);
            return userService.getUserInfoByUserCode(UserAuthConstant.APP_SOURCE_JDMS, resultResponse.getData().toString());
        } else {
            throw new ServiceBizException("此jwt 不合法");
        }
    }
}
